/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 jfinal app. jfapp Group.
 */


define(['adminapp','jquery-validation', 'jquery-validation-additional',
    'custom/zh_validator'], function ($app) {
    var __type__ = {
        click : 'click',
        view : 'view'
    };
    var judgeType = function(viewOrUrl) {
        if (!viewOrUrl) {
            return __type__.click;
        }
        if (viewOrUrl.indexOf('http') == 0 || viewOrUrl.indexOf('https') == 0) {
            return __type__.view;
        } else {
            return __type__.click;
        }
    };
    $app.navactive('wx_menu');

    var menuTable = $("#menuTable");

    g.oneleveltpl = '#one-level-template';
    g.twoleveltpl = '#two-level-template';
    g.alerttpl = '#alert-template';

    var alerttpl = Handlebars.compile($(g.alerttpl).html());
    var oneleveltpl = Handlebars.compile($(g.oneleveltpl).html());
    var twoleveltpl = Handlebars.compile($(g.twoleveltpl).html());

    var $menuTable = $('#menuTable');

    var tip = function(content) {
        var $tip = $("#tip");
        $tip.empty();
        $tip.append(content);
    };

    //验证有没有尚未保存的
    var checksave = function(oneLevelMenus) {
        if (!oneLevelMenus || oneLevelMenus.length == 0) {
            return true;
        }
        var ok = true;
        $(oneLevelMenus).each(function(k,v) {
            var line = $(v).attr("line");
            var id = $(v).find('input[name="id-'+ line +'"]').val();
            if (!id || id == "") {
                ok = false;
                return;
            }
            var twoLevelMenus = $(v).find('tr[name="two-level"]');
            $(twoLevelMenus).each(function(i,o) {
                var _line = $(o).attr("line");
                var _id = $(o).find('input[name="id-'+ _line +'"]').val();
                if (!_id || _id == "") {
                    ok = false;
                    return;
                }
            });
        });
        return ok;
    }

    //一级菜单按钮事件
    $("#addOneLevel").click(function() {
        var oneLevelMenus = $('tbody[name="one-level"]');
        if (oneLevelMenus && oneLevelMenus.length >= 3) {
            var context = {classname : 'alert-warning', message : '一级菜单最多3个'};
            tip(alerttpl(context));
            return;
        }

        if (!checksave(oneLevelMenus)) {
            var context = {classname : 'alert-warning', message : '请先保存菜单'};
            tip(alerttpl(context));
            return;
        }

        var _name = new Date().getTime();
        menuTable.append(oneleveltpl({line : _name, name : new Date().getTime()}));
        tip("");
    });

    //二级菜单按钮事件
    $menuTable.delegate('a[name=addTwoLevel]', 'click', function() {
        var line = $(this).attr("line");
        var tbody = $('tbody[line="'+ line +'"]');

        var twoLevelMenus = tbody.find('tr[name="two-level"]');
        if (twoLevelMenus && twoLevelMenus.length >= 5) {
            var context = {classname : 'alert-warning', message : '二级菜单最多5个'};
            tip(alerttpl(context));
            return;
        }

        if (!checksave($('tbody[name="one-level"]'))) {
            var context = {classname : 'alert-warning', message : '请先保存菜单'};
            tip(alerttpl(context));
            return;
        }

        var _name = new Date().getTime();
        tbody.append(twoleveltpl({line : _name, name : new Date().getTime()}));
        tip("");
    });


    //保存
    $menuTable.delegate('a[name=save]', 'click', function() {
        var line = $(this).attr("line");
        var level = $(this).attr("level");
        var $menu = null;
        if (level == 'one') {
            $menu = $('tbody[line="'+ line +'"]');
        } else {
            $menu = $('tr[line="'+ line +'"]');
        }

        var check = $("#menuForm").validate().form();

        if (check) {
            var id = $($menu).find('input[name="id-'+ line +'"]').val();
            var name = $($menu).find('input[name="name-'+ line +'"]').val();
            var viewUrl = $($menu).find('input[name="view-url-'+ line +'"]').val();
            viewUrl = $.trim(viewUrl);
            var params = {'menu.id' : id, 'menu.name' : name};

            var t = judgeType(viewUrl);
            if (t == __type__.click) {
                params = $.extend(params, {'menu.menu_type' : __type__.click, 'menu.evt' : viewUrl});
            } else {
                params = $.extend(params, {'menu.menu_type' : __type__.view, 'menu.url_path' : viewUrl});
            }

            if (level == 'two') {
                var pEl = $menu.parent();
                var pLine = $(pEl).attr("line");
                var parent = $(pEl).find('input[name="id-'+ pLine +'"]').val();
                params = $.extend(params, {'menu.parent' : parent});
            }

            $.post(g.ctx + "admin/wx/menu/save", params, function(msg) {
                var context;
                if (msg.status == 'OK') {
                    $($menu).find('input[name="id-'+ line +'"]').val(msg.data.id);
                    context = {classname : 'alert-success', message : msg.message};
                } else {
                    context = {classname : 'alert-warning', message : msg.message};
                }
                tip(alerttpl(context));
            });
        }
    });

    //删除
    $menuTable.delegate('a[name=remove]', 'click', function() {
        var line = $(this).attr("line");
        var level = $(this).attr("level");
        var $menu = null;
        if (level == 'one') {
            $menu = $('tbody[line="'+ line +'"]');
        } else {
            $menu = $('tr[line="'+ line +'"]');
        }
        var id = $($menu).find('input[name="id-'+ line +'"]').val();
        if (!id || id == "") { //没有ID直接页面删除
            $menu.remove();
            return;
        }
        $.post(g.ctx + "admin/wx/menu/delete", {id : id}, function(msg) {
            var context;
            if (msg.status == 'OK') {
                $menu.remove();
                context = {classname : 'alert-success', message : msg.message};
            } else {
                context = {classname : 'alert-warning', message : msg.message};
            }
            tip(alerttpl(context));
        });
    });

    //生成自定义菜单
    //生成自定义菜单
    $("#create").click(function() {
        $.post(g.ctx + "admin/wx/menu/create", {}, function(msg) {
            var context;
            if (msg.status == 'OK') {
                context = {classname : 'alert-success', message : msg.message};
            } else {
                context = {classname : 'alert-warning', message : msg.message};
            }
            tip(alerttpl(context));
        });
    })
    //删除自定义菜单
    $("#revoke").click(function() {
        $.post(g.ctx + "admin/wx/menu/revoke", {}, function(msg) {
            var context;
            if (msg.status == 'OK') {
                context = {classname : 'alert-success', message : msg.message};
            } else {
                context = {classname : 'alert-warning', message : msg.message};
            }
            tip(alerttpl(context));
        });
    })

    //添加菜单内容
    $menuTable.delegate('a[name="message"]', 'click', function() {
        var line = $(this).attr("line");
        var level = $(this).attr("level");
        var $menu = null;
        if (level == 'one') {
            $menu = $('tbody[line="'+ line +'"]');
        } else {
            $menu = $('tr[line="'+ line +'"]');
        }
        var id = $($menu).find('input[name="id-'+ line +'"]').val();
        if (!id || id == "") { //没有ID直接页面删除
            var context = {classname : 'alert-warning', message : '请先保存菜单'};
            tip(alerttpl(context));
            return;
        }
        var viewUrl = $($menu).find('input[name="view-url-'+ line +'"]').val();
        if(!viewUrl) {
            var context = {classname : 'alert-warning', message : '请输入响应关键字'};
            tip(alerttpl(context));
            return;
        }
        /*var t = judgeType(viewUrl);
        if (t == __type__.view) {
            var context = {classname : 'alert-warning', message : '当前菜单为view类型，无法回复内容'};
            tip(alerttpl(context));
            return;
        }*/
        window.location.href = g.ctx + "admin/wx/menu/message/" + id;
    });
});

